package com.ltedu.sms.service.impl;

import com.ltedu.common.contants.Constants;
import com.ltedu.common.enums.ErrorCodeEnum;
import com.ltedu.common.redis.RedisTool;
import com.ltedu.common.utils.CodeUtils;
import com.ltedu.common.vo.Result;
import com.ltedu.sms.domain.SendSmsLog;
import com.ltedu.sms.service.SendSmsLogService;
import com.ltedu.sms.service.SendSmsService;
import com.ltedu.sms.utils.SendSmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: SendSmsServiceImpl
 * @auther: Jerry
 * @date: 2020/11/20 15:53
 * @desctiption: 短信发送接口实现类
 * @version: 1.0
 */
@Service
public class SendSmsServiceImpl implements SendSmsService {

    private Logger logger = LoggerFactory.getLogger(SendSmsServiceImpl.class);

    @Autowired
    private RedisTool redisTool;

    @Autowired
    private SendSmsLogService sendSmsLogService;

    /**
     * 发送短信
     *
     * @param phone 电话
     * @return {@link Result}
     */
    @Override
    public Result sendSms(String phone) {
        logger.info("SendSmsService.send...phone:{}", phone);
        if (StringUtils.isEmpty(phone)) { return Result.fail(ErrorCodeEnum.MOBILE_IS_NOT_NULL); }
        String  code = (String) redisTool.get(Constants.SEND_SMS_KEY + phone);
        if (StringUtils.isNotEmpty(code)) {
            return Result.ok();
        }
        // 创建短信模板
        String templateCode = SendSmsUtils.TemplateCode;
        // 生成的随机验证码
        code = CodeUtils.generateCode();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        logger.info("SendSmsService.send...code:{}", code);
        boolean result = SendSmsUtils.sendSms(phone, templateCode, param);
        // 插入短信日志
        SendSmsLog sendSmsLog = new SendSmsLog();
        sendSmsLog.setMobile(phone);
        sendSmsLog.setSmsCode(code);
        sendSmsLog.setTemplate(templateCode);
        sendSmsLog.setGmtCreate(new Date());
        sendSmsLog.setSuccess(result ? Constants.NORMAL : Constants.FROZEN);
        sendSmsLogService.save(sendSmsLog);
        if (result) {
            redisTool.setWithTime(Constants.SEND_SMS_KEY + phone, code, 5*60L );
            return Result.ok();
        }
        return Result.fail(ErrorCodeEnum.SMS_SENDING_FAIL);
    }
}
